const {
  modelStudent,
  modelTeacher, 
  modelCourse, 
  modelScore,
  modelMenu,
  modelSdept,
  modelClass,
  modelStudentCourse,
  modelMenuRole,
  modelCourseTeacher,
  modelRole,
  modelSdeptCourse
} = require('@/moudels/school.collection')

class SchoolService {
  async roleService() {
    const res = await modelRole.find()
    return res ? res : null
  }
  async addRoleService(data) {
    let res;
    let setData = {
      name: data.name,
      description: data.description,
      level: data.level
    }
    if (data.isEdit) {
      const sdept = {
        _id: data.id
      }
      res = await modelRole.updateOne(sdept, {$set: setData})
    } else {
      res = await modelRole.create(setData)
    }
    return res ? res : null
  }
  async delRoleService(data) {
    let res = await modelRole.deleteOne(data)
    return res ? res : null
  }
  async sdeptService(id) {
    const res = await modelSdept.find(id)
    return res ? res : null
  }
  async addSdeptService(sdept) {
    const res = await modelSdept.create(sdept)
    return res ? res : null
  }
  async editSdeptService(sdept, upSdept) {
    const res = await modelSdept.updateOne(sdept, {$set: upSdept})
    return res ? res : null
  }
  async delSdeptService(sdept) {
    const res = await modelSdept.deleteOne(sdept)
    return res ? res : null
  }
  async classService(sdeptid) {
    const res = await modelClass.find(sdeptid)
    return res ? res : null
  }
  async addClassService(classs) {
    const res = await modelClass.create(classs)
    return res ? res : null
  }
  async editClassService(_id, upSet) {
    const res = await modelClass.updateOne(_id, {$set: upSet})
    return res ? res : null
  }
  async delClassService(_id) {
    const res = await modelClass.deleteOne(_id)
    return res ? res : null
  }
  async studentListService(class_name) {
    const res = await modelStudent.find(class_name)
    return res ? res : null
  }
  // 新建学生
  async insertStudentService(strdent) {
    const res = await modelStudent.create(strdent)
    return res ? res : null
  }
  // 新建学生课程
  async insertStudentCourese(strdentCourese) {
    const res = await modelStudentCourse.create(strdentCourese)
    return res ? res : null
  }
  async teacherListService() {
    const res = await modelTeacher.find()
    return res ? res : null
  }
  // 查询所有课程
  async courseService() {
    const res = await modelCourse.find()
    return res ? res : null
  }
  // 新增课程
  async addCourseService(data) {
    const res = await modelCourse.create(data)
    return res ? res : null
  }
  // 编辑课程
  async editCourseService(data) {
    const {_id} = data
    const res = await modelCourse.updateOne({_id}, {$set: data})
    return res ? res : null
  }
  // 删除课程
  async delCourseService(_id) {
    const res = await modelCourse.deleteOne(_id)
    return res ? res : null
  }
  // 新增老师对应的课程
  async addTeacherCourseService(data) {
    const res = await modelCourseTeacher.create(data)
    return res ? res : null
  }
  // 编辑老师对应的课程
  async editTeacherCourseService(data) {
    const {_id} = data
    const res = await modelCourseTeacher.updateOne({_id},{$set: data})
    return res ? res : null
  }
  // 删除老师对应的课程
  async delTeacherCourseService(_id) {
    const res = await modelCourseTeacher.deleteOne(_id)
    return res ? res : null
  }
  // 查询老师对应的课程
  async teacherToCourseService() {
    const res = await modelCourseTeacher.aggregate([
      {
        $lookup: {
          from: 'course',
          localField: 'cour_id',
          foreignField: 'cour_id',
          as: 'course'
        }
      },
      {
        $lookup: {
          from: 'teacher',
          localField: 'tea_id',
          foreignField: 'tea_id',
          as: 'teacher'
        }
      },
      {
        $project: {
          cour_id: 1,
          tea_id: 1,
          cour_name: '$course.cour_name',
          tea_name: '$teacher.tea_name',
        }
      }
    ])
    return res ? res : null
  }
  // 查询学生成绩
  async studentScoreService({cour_name, stu_name, class_name, sdept_name}) {
    const whereOpt = {}

    cour_name && Object.assign(whereOpt, { cour_name })
    stu_name && Object.assign(whereOpt, { stu_name })
    class_name && Object.assign(whereOpt, { class_name })
    sdept_name && Object.assign(whereOpt, { sdept_name })

    const res = await modelScore.aggregate([
      {
        $lookup: {
          from: 'student',
          localField: 'stu_id',
          foreignField: 'stu_id',
          as: 'student'
        }
      },
      {
        $unwind: "$student"
      },
      {
        $lookup: {
          from: 'course',
          localField: 'cour_id',
          foreignField: 'cour_id',
          as: 'course'
        }
      },
      {
        $unwind: "$course"
      },
      {
        $project: {
          sco_score: 1,
          class_name: '$student.class_name',
          sdept_name: '$student.sdept_name',
          stu_id: '$student.stu_id',
          stu_name: '$student.stu_name',
          stu_age: '$student.stu_age',
          stu_gander: '$student.stu_gander',
          stu_address: '$student.stu_address',
          cour_id: '$course.cour_id',
          cour_name: '$course.cour_name',
        }
      },
      // 查询所有集合中为 "语文" 的集合
      {
        $match: whereOpt
      },
      {
        $sort: {
          sco_score: -1
        }
      }
    ])
    return res ? res : null
  }
  // 查询最高分
  async maxScoreService() {
    const res = await modelCourse.aggregate([
      {
        $lookup:{
          from: 'score',
          localField: 'cour_id',
          foreignField: 'cour_id',
          as: 'item'
        }
      },
      {
        $unwind: "$item"
      },
      {
        $group: {
          _id:'$cour_name',
          cour_id: { $first: "$cour_id" }, 
          cour_name: { $first: "$cour_name" }, 
          sco_score:{$max:'$item.sco_score'}
        }
      },
      {
        $project:{
          _id: 0
        }
      }
    ])
    return res ? res : null
  }
  // 学生对应课程
  async studentCourseRelation() {
    const res = await modelStudentCourse.aggregate([
      {
        $lookup: {
          from: "student",
          localField: "stu_id",
          foreignField: "stu_id",
          as: "student"
        }
      },
      {
        $unwind: "$student"
      },
      {
        $lookup: {
          from: 'course',
          localField: "cour_id",
          foreignField: "cour_id",
          as: "course"
        }
      },
      {
        $unwind: "$course"
      },
      {
        $lookup: {
          from: 'teacher',
          localField: "tea_id",
          foreignField: "tea_id",
          as: "teacher"
        }
      },
      {
        $unwind: "$teacher"
      },
      {
        $project: {
          stu_id: 1,
          cour_id: 1,
          stu_name: "$student.stu_name",
          class_name: "$student.class_name",
          cour_name: "$course.cour_name",
          tea_id: "$course.tea_id",
          tea_name: "$teacher.tea_name"
        }
      },
      // {
      //   $unionWith: {
      //       coll: "teacher", pipeline: [{
      //           $project: { tea_id: 1, tea_name: 1, _id: 0 }
      //       }]
      //   }
      // },
    ])
    return res ? res : null
  }
  // 添加权限
  async addMenuRoleService(data) {
    const res = await modelMenuRole.create(data)
    return res ? res : null
  }
  // 删除权限
  async delMenuRoleService(data) {
    console.log(data)
    const res = await modelMenuRole.deleteOne(data)
    return res ? res : null
  }
  // 修改权限
  async editMenuRoleService(data) {
    const res = await modelMenuRole.updateOne(
      { 'role_id': data.level }, 
      {$set: { 'menu_id': data.menu }}
    )
    return res ? res : null
  }
  async menuRService(role_level) {
    const res = await modelMenuRole.aggregate([
      {
        $match: {
          role_id: Number(role_level)
        }
      },
      // {
      //   $unwind: "$menu_id"
      // },
      {
        $lookup: {
          from: 'menu',
          localField: 'menu_id',
          foreignField: 'en_name',
          as: 'menus'
        }
      },
      {
        $unwind: "$menus"
      },
      {
        $project: {
          name: "$menus.name",
          en_name: "$menus.en_name",
          children: {
            $filter: {
              input: "$menus.children",
              as: 'childrens',
              cond: {// en_name 是否在 menu_id中
                $in: ["$$childrens.en_name", "$menu_id"]
              }
            }
          }
        }
      }
    ])
    return res ? res : null
  }
  async menuService() {
    const res = await modelMenu.find()
    return res ? res : null
  }
  async insertMenuService(data) {
    const res = await modelMenu.create(data)
    return res ? res : null
  }
  async editMenuService(data) {
    let oldObj = {}
    let newObj = {}
    if (data.parent) {
      oldObj = data.isEdit ? 
        { 'children.en_name': data.en_name } : 
        { 'en_name': data.parent }
      newObj = data.isEdit ?
        {$set: { 'children.$.name': data.name }} :
        {$addToSet: { 'children': {name:data.name, en_name: data.en_name} }}
    } else {
      oldObj = { 'en_name': data.en_name }
      newObj = { 'name': data.name }
    }
    const res = await modelMenu.updateOne(oldObj, newObj)
    return res ? res : null
  }
  async delMenuService(data) {
    let res
    if (data.parent) {
      res = await modelMenu.updateOne(
        { 'en_name': data.parent },
        { $pull: { 'children': {name:data.name, en_name: data.en_name} }}
      )
    } else {
      res = await modelMenu.deleteOne(data)
    }
    return res ? res : null
  }
  // 查询院系必须课
  async getSdeptToCourseService(param) {
    const res = await modelSdeptCourse.find(param)
    return res ? res : null
  }
  async editSdeptToCourseService(param) {
    const {name} = param
    let res
    const resfind = await modelSdeptCourse.find({name})
    console.log('==resfind==',resfind)
    if (resfind.length) {
      res = await modelSdeptCourse.updateOne(
        {'name': param.name}, 
        { $set: {'cour_id': param.cour_id}
      })
    } else {
      res = await modelSdeptCourse.create(param)
    }
    return res ? res : null
  }
}

module.exports = new SchoolService()